package ac.biu.nlp.nlp.curator.client.rtesum;

import java.io.File;
import java.io.FileFilter;

import org.apache.thrift.TException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import ac.biu.nlp.nlp.curator.client.CuratorClientException;

import edu.illinois.cs.cogcomp.thrift.base.AnnotationFailedException;
import edu.illinois.cs.cogcomp.thrift.base.ServiceUnavailableException;
import eu.excitementproject.eop.common.utilities.datasets.rtesum.Rte6mainIOException;

/**
 * 
 * @author Asher Stern
 * @since Mar 24, 2013
 *
 */
public class RteSumDatasetSrl
{
	public static final String CORPUS_DIR_NAME = "Corpus";
	public static final String TOPIC_DIR_PREFIX = "Topic";
	
	public RteSumDatasetSrl(Document xmlDocument, String host, int port, File datasetDir)
	{
		super();
		this.xmlDocument = xmlDocument;
		this.host = host;
		this.port = port;
		this.datasetDir = datasetDir;
	}

	public void process() throws ServiceUnavailableException, AnnotationFailedException, TException, Rte6mainIOException, CuratorClientException
	{
		Element rootElement = xmlDocument.createElement("srl");
		xmlDocument.appendChild(rootElement);
		File[] allTopics = datasetDir.listFiles(new FileFilter()
		{
			
			@Override
			public boolean accept(File pathname)
			{
				if (pathname.isDirectory())
				{
					if (pathname.getName().startsWith(TOPIC_DIR_PREFIX))
						return true;
				}
				return false;
			}
		});
		
		for (File topicDir : allTopics)
		{
			System.out.println("Process topic "+topicDir.getPath());
			Element topicElement = xmlDocument.createElement("topic");
			topicElement.setAttribute("topic-directory", topicDir.getName());
			rootElement.appendChild(topicElement);
			processTopic(topicDir,topicElement);
		}
	}
	
	private void processTopic(File topicDir, Element topicElement) throws ServiceUnavailableException, AnnotationFailedException, TException, Rte6mainIOException, CuratorClientException
	{
		File corpusDir = new File(topicDir,CORPUS_DIR_NAME);
		File[] documentFiles = corpusDir.listFiles(new FileFilter()
		{
			@Override
			public boolean accept(File pathname)
			{
				if (pathname.isFile())
				{
					if (pathname.getPath().endsWith(".xml"))
					{
						return true;
					}
				}
				return false;
			}
		});
		
		for (File documentFile : documentFiles)
		{
			System.out.println("\tProcess document "+documentFile.getPath());
			Element documentXmlElement = xmlDocument.createElement("document");
			topicElement.appendChild(documentXmlElement);
			documentXmlElement.setAttribute("file-name",documentFile.getName());
			
			RteSumDocumentSrl srl =
					new RteSumDocumentSrl(documentFile,xmlDocument,documentXmlElement,host,port);
			srl.process();
		}
		
	}
	
	

	private Document xmlDocument;
	private String host;
	private int port;
	private File datasetDir;
}
